﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using MySql.Data.Common;

namespace Tel_Mes_Interface
{
    //, _codeCmd;




    public static class ResultEnum
    {
        //'-1^异常原因的文字说明^0^0^异常原因英文'-----------------表示异常
        public static string _Exception
        {
            get
            {
                return "-1^{0}^0^0^{1}";
            }
        }

        //'0^1^假品信息^0^假品信息英文信息'------------------------表示不存在
        //'0^2^假品信息^0^假品信息英文信息'------------------------表示不存在,有非数字码
        //'0^3^假品信息^0^假品信息英文信息'------------------------表示不存在,防伪码长度不为20位
        public static string _NotFoundResult
        {
            get
            {
                return "0^{0}^{1}^0^{2}'";
            }
        }

        //'1^真品信息^0^0^真品信息英文回复'------------------------表示存在(首次查询)
        //'2^真品信息^首次查询日期^首次查询时间^真品信息英文回复'------------------------表示在，可能为假品(真品非首次查询)
        public static string _NormalResult
        {
            get
            {
                return "{0}^{1}^{2}^{2}^{3}";
            }
        }

        //'3^0^0^0^0'----------------------------------------------表示存在，被人为停止查询
        //'4^0^0^0^0'----------------------------------------------表示存在,但不在有效查询期内
        public static string _NotAuth
        {
            get
            {
                return "{0}^0^0^0^0";
            }
        }
    }
    public class DB_Service
    {
        /// <summary>
        /// 主库连接
        /// </summary>
        private MySqlConnection _mainConnection;
        private MySqlCommand __maincmd;
        private MySqlCommand _mianCmd
        {
            get
            {
                try
                {
                    if (__maincmd == null)
                    {
                        _mainConnection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Mgj_MainCode"].ConnectionString);
                        _mainConnection.Open();
                        __maincmd = _mainConnection.CreateCommand();
                    }
                    return __maincmd;
                }
                catch
                {
                    return null;
                }
            }
        }

        private MySqlConnection _codeConnection;
        private MySqlCommand __codecmd;
        private MySqlCommand _codeCmd
        {
            get
            {
                try
                {
                    if (__codecmd == null)
                    {
                        _codeConnection = new MySqlConnection(ConfigurationManager.ConnectionStrings["Mgj_CoeeDb"].ConnectionString);
                        _codeConnection.Open();
                        __codecmd = _codeConnection.CreateCommand();
                    }
                    return __codecmd;
                }
                catch
                {
                    return null;
                }
            }
        }


        public string FwVerifiction(string code, string value, int type)
        {
            string _result = string.Empty;
            if (_mianCmd == null || _codeCmd == null)
            {
                return "-1^系统初始化失败^0^0^System initialization failed";
            }
            _mianCmd.CommandType = CommandType.Text;//初始化
            _codeCmd.CommandType = CommandType.Text;//初始化
            //逻辑开始
            string searchcode = string.Empty;

            if (!string.IsNullOrEmpty(code))
            {
                searchcode = Mima.Jiemi(code, AppConst.DigitCodeKey);
            }
            searchcode = searchcode.Substring(0, 6);
            string sql = string.Format(@"SELECT
	                                      A.Fw_CodeSecret,
	                                      A.EnterpriseId,
	                                      A.ProductId,
                                          A.Flag,
                                          B.EnterpriseName,
                                          COUNT(C.ID) HSearchCount,
                                          C.QueryTime
                                       FROM
	                                  nbcodemain.antifake_digitcode{0} A
                                      LEFT JOIN organization_enterprise B ON A.EnterpriseId = B.ID
                                      LEFT JOIN antifake_querycodelog C ON A.Fw_CodeSecret = C.Fw_Code
                                      WHERE
	                                  A.Fw_CodeSecret ='{1}'", searchcode, code);
            _mianCmd.CommandText = sql;
            List<ResultModel> resultmodel = new List<ResultModel>();
            try
            {
                MySqlDataReader reader = _mianCmd.ExecuteReader();
                while (reader.Read())
                {
                    resultmodel.Add(new ResultModel
                    {
                        Fw_CodeSecret = reader["Fw_CodeSecret"].ToString(),
                        EnterpriseId = reader["EnterpriseId"].ToString(),
                        ProductId = reader["ProductId"].ToString(),
                        Flag = reader["Flag"].ToString(),
                        EnterpriseName = reader["EnterpriseName"].ToString(),
                        HSearchCount = reader["HSearchCount"].ToString(),
                        QueryTime = reader["QueryTime"].ToString()
                    });
                }
                reader.Close();
            }
            catch { }
            string _valid = resultmodel.Count == 0 ? "0" : resultmodel.FirstOrDefault().Flag;
            ResultModel __result_model = resultmodel.FirstOrDefault();
            string _productId = "0", _enterpriseId = "0", _net_content = string.Empty, _tel_content = string.Empty, _sms_content = string.Empty;
            if (__result_model != null)
            {
                _productId = __result_model.ProductId;
                _enterpriseId = __result_model.EnterpriseId;

                sql = string.Format(@"SELECT Query_Result_Content,Query_Tel_Content,Query_Message_Content FROM codemanage_gencode  WHERE  PatchId =
                           (SELECT	ID FROM	codemanage_gencodebatch E WHERE	E.EnterpriseId = {0} AND E.Batch = {1}) AND EnterpriseId={0}", __result_model.EnterpriseId, searchcode.Substring(4, 2));

                _mianCmd.CommandText = sql;
                MySqlDataReader _readers = _mianCmd.ExecuteReader();
                while (_readers.Read())
                {
                    _net_content = _readers["Query_Result_Content"].ToString();
                    _tel_content = _readers["Query_Tel_Content"].ToString();
                    _sms_content = _readers["Query_Message_Content"].ToString();
                }
                _readers.Close();
            }
            _mianCmd.CommandText = string.Format(@"INSERT INTO antifake_querycodelog (
	                                             `Fw_Code`,
	                                             `QueryType`,
	                                             `QueryValue`,
	                                             `QueryTime`,
	                                             `QueryMessage`,
	                                             `Valid`,
	                                             `QueryProvince`,
	                                             `QueryCity`,
	                                             `ProductId`,
	                                             `EnterpriseId`
                                                  )
                                                 VALUES
	                                             ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')",
             code, type, value, DateTime.Now, "", _valid, "", "", _productId, _enterpriseId);
            _mianCmd.ExecuteNonQuery();
            //逻辑结束
            _codeCmd.Dispose(); _mianCmd.Dispose();//
            _mainConnection.Close(); _codeConnection.Close();
            if (type != 2)
            {
                if (resultmodel.Count == 0)
                {
                    return string.Format(ResultEnum._Exception, "该码不正确", "The code is incorrect");
                }
                if (__result_model.Flag == "0")
                {
                    return string.Format(ResultEnum._NotAuth, "3");
                }
                if (__result_model.HSearchCount != "0")
                {
                    return string.Format(ResultEnum._NormalResult, "2", "您的产品已被查询多次，谨防假冒", __result_model.QueryTime, "Your product has been queried many times, beware of counterfeiting");
                }
                return string.Format(ResultEnum._NormalResult, "1", "尊敬的客户您好！您所查询的是" + __result_model.EnterpriseName + "的产品，是正牌产品的标识，欢迎您再次选购！", "0", "");
            }
            else
            {
                if (resultmodel.Count == 0 ||  __result_model.Flag == "0")
                {
                    return string.Format(ResultEnum._Exception, @"D:\码管家防伪语音\000244.voc", @"D:\码管家防伪语音\000244.voc");
                }
                if (__result_model.HSearchCount != "0")
                {
                    return string.Format(ResultEnum._NormalResult, "2", @"D:\码管家防伪语音\000244.voc", __result_model.QueryTime, @"D:\码管家防伪语音\000244.voc");
                }
                return string.Format(ResultEnum._NormalResult, "1", @"D:\码管家防伪语音\000244.voc", "0", "");
            }
        }
    }

    public class ResultModel
    {
        public string Fw_CodeSecret { get; set; }
        public string EnterpriseId { get; set; }
        public string ProductId { get; set; }
        public string Flag { get; set; }
        public string EnterpriseName { get; set; }
        public string HSearchCount { get; set; }
        public string QueryTime { get; set; }
    }

    //public static class ReaderObject
    //{
    //    public static IEnumerable<T> ConvertEnumerable<T>(MySqlDataReader reader) where T : class,new()
    //    {
    //        var returnList = new List<T>();

    //        var result = new Object();

    //        while (reader.Read())
    //        {
    //            result = ConvertReader<T>(reader);
    //            if (result == null)
    //            {
    //                returnList.Add(default(T));
    //            }
    //            else
    //            {
    //                returnList.Add((T)result);
    //            }
    //        }

    //        return returnList;
    //    }

    //    private static object ConvertReader<T>(MySqlDataReader reader) where T : class,new()
    //    {
    //        object result = null;
    //        if (typeof(bool) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(bool));
    //        }
    //        else if (typeof(byte) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(byte));
    //        }
    //        else if (typeof(char) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(char));
    //        }
    //        else if (typeof(DateTime) == typeof(T) || typeof(DateTime?) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(DateTimeOffset));
    //        }
    //        else if (typeof(decimal) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(decimal));
    //        }
    //        else if (typeof(double) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(double));
    //        }
    //        else if (typeof(float) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(float));
    //        }
    //        else if (typeof(Guid) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(Guid));
    //        }
    //        else if (typeof(short) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(short));
    //        }
    //        else if (typeof(int) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(int));
    //        }
    //        else if (typeof(string) == typeof(T))
    //        {
    //            result = ReaderElement(reader, 0, typeof(string));
    //        }
    //        else
    //        {
    //            result = System.Activator.CreateInstance<T>();
    //            int i = 0;
    //            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(result))
    //            {
    //                try
    //                {
    //                    property.SetValue(result, ReaderElement(reader, i, property.PropertyType));
    //                    i++;
    //                }
    //                catch (Exception ex)
    //                {
    //                    throw new ArgumentException("绑定属性【" + property.Name + "】发生异常:" + ex.Message);
    //                }
    //            }
    //        }
    //        return result;
    //    }

    //    public static object ReaderElement(MySqlDataReader reader, int count, Type type)
    //    {
    //        if (typeof(bool) == type)
    //        {
    //            return reader.GetBoolean(count);
    //        }
    //        else if (typeof(byte) == type)
    //        {
    //            return reader.GetByte(count);
    //        }
    //        else if (typeof(char) == type)
    //        {
    //            return reader.GetChar(count);
    //        }
    //        else if (typeof(DateTime) == type || typeof(DateTime?) == type)
    //        {
    //            object ra = reader[count];
    //            if (ra is DBNull)
    //            {
    //                return new DateTime?();
    //            }
    //            return ra;
    //        }
    //        else if (typeof(decimal) == type || typeof(int?) == type)
    //        {
    //            object ra = reader[count];
    //            if (ra is DBNull)
    //            {
    //                return new decimal?();
    //            }
    //            return ra;
    //        }
    //        else if (typeof(double) == type)
    //        {
    //            return reader.GetDouble(count);
    //        }
    //        else if (typeof(float) == type)
    //        {
    //            return reader.GetFloat(count);
    //        }
    //        else if (typeof(Guid) == type)
    //        {
    //            return reader.GetGuid(count);
    //        }
    //        else if (typeof(short) == type)
    //        {
    //            return reader.GetInt16(count);
    //        }
    //        else if (typeof(int) == type || typeof(int?) == type)
    //        {
    //            object ra = reader[count];
    //            if (ra is DBNull)
    //            {
    //                return new int?();
    //            }
    //            return ra;
    //        }
    //        else if (typeof(long) == type)
    //        {
    //            return reader.GetInt64(count);
    //        }
    //        else
    //        {
    //            return reader.IsDBNull(count) ? null : reader.GetString(count);
    //        }
    //    }
    //}

}

